<template>
  <div class="setmeal-container">
    <div class="filter-container">
      <el-form :inline="true" :model="filterForm" class="form-inline">
        <el-form-item label="套餐名称">
          <el-input v-model="filterForm.name" placeholder="请输入套餐名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="套餐分类">
          <el-select v-model="filterForm.categoryId" placeholder="请选择" clearable>
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="请选择" clearable>
            <el-option label="启用" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <div class="operation-container">
      <el-button type="primary" @click="handleAdd">新增套餐</el-button>
      <!-- <el-button type="success" :disabled="!multipleSelection.length" @click="handleBatchEnable">批量启用</el-button> -->
      <!-- <el-button type="info" :disabled="!multipleSelection.length" @click="handleBatchDisable">批量禁用</el-button> -->
      <el-button type="danger" :disabled="!multipleSelection.length" @click="handleBatchDelete">批量删除</el-button>
    </div>
    
    <el-table
      :data="setmealList"
      border
      style="width: 100%"
      v-loading="loading"
      @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column
        prop="name"
        label="套餐名称"
        width="180">
      </el-table-column>
      <el-table-column
        prop="image"
        label="图片"
        width="120">
        <template slot-scope="scope">
          <el-image 
            style="width: 60px; height: 60px"
            :src="scope.row.image" 
            fit="cover"
            :preview-src-list="[scope.row.image]">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column
        prop="categoryName"
        label="分类"
        width="120">
      </el-table-column>
      <el-table-column
        prop="price"
        label="价格"
        width="120">
        <template slot-scope="scope">
          ¥{{ scope.row.price.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="status"
        label="状态"
        width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        prop="updateTime"
        label="更新时间"
        width="180">
      </el-table-column>
      <el-table-column
        label="操作"
        width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { getSetmealPage, updateSetmealStatus, deleteSetmeal } from '@/api/setmeal'
import { getCategoryList } from '@/api/category'

export default {
  name: 'SetmealManagement',
  data() {
    return {
      // 筛选表单
      filterForm: {
        name: '',
        categoryId: '',
        status: ''
      },
      // 分类选项
      categoryOptions: [],
      // 套餐列表
      setmealList: [],
      // 多选
      multipleSelection: [],
      // 加载状态
      loading: false,
      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0
    }
  },
  created() {
    // 获取分类列表
    this.fetchCategoryOptions()
    // 获取套餐列表
    this.fetchSetmealList()
  },
  methods: {
    // 获取分类选项
    fetchCategoryOptions() {
      // 获取套餐分类（type=2）
      getCategoryList(2)
        .then(res => {
          if (res.code === 1) {
            this.categoryOptions = res.data || []
          } else {
            this.$message.error(res.msg || '获取分类列表失败')
          }
        })
        .catch(err => {
          console.error('获取分类列表失败', err)
          this.$message.error('获取分类列表失败')
        })
    },
    // 获取套餐列表
    fetchSetmealList() {
      this.loading = true
      const params = {
        page: this.currentPage,
        pageSize: this.pageSize,
        name: this.filterForm.name,
        categoryId: this.filterForm.categoryId,
        status: this.filterForm.status
      }

      if (params.name === '') delete params.name
      if (params.categoryId === '') delete params.categoryId
      if (params.status === '') delete params.status
      
      getSetmealPage(params)
        .then(res => {
          if (res.code === 1) {
            this.setmealList = res.data.records || []
            this.total = res.data.total || 0
          } else {
            this.$message.error(res.msg || '获取套餐列表失败')
          }
        })
        .catch(err => {
          console.error('获取套餐列表失败', err)
          this.$message.error('获取套餐列表失败')
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 查询
    handleSearch() {
      this.currentPage = 1
      this.fetchSetmealList()
    },
    // 重置表单
    resetForm() {
      this.filterForm = {
        name: '',
        categoryId: '',
        status: ''
      }
      this.handleSearch()
    },
    // 新增套餐
    handleAdd() {
      this.$router.push('/setmeal/add')
    },
    // 编辑套餐
    handleEdit(row) {
      this.$router.push(`/setmeal/edit/${row.id}`)
    },
    // 删除套餐
    handleDelete(row) {
      this.$confirm('确认删除该套餐?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        deleteSetmeal(row.id)
          .then(res => {
            if (res.code === 1) {
              this.$message.success('删除成功')
              this.fetchSetmealList()
            } else {
              this.$message.error(res.msg || '删除失败')
            }
          })
          .catch(err => {
            console.error('删除套餐失败', err)
            this.$message.error('删除套餐失败')
          })
          .finally(() => {
            this.loading = false
          })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    /* // 批量启用
    handleBatchEnable() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请至少选择一项')
        return
      }
      
      this.$confirm(`确认启用选中的${this.multipleSelection.length}个套餐?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        const ids = this.multipleSelection.map(item => item.id).join(',')
        updateSetmealStatus(ids, 1)
          .then(res => {
            if (res.code === 1) {
              this.$message.success('批量启用成功')
              this.fetchSetmealList()
            } else {
              this.$message.error(res.msg || '批量启用失败')
            }
          })
          .catch(err => {
            console.error('批量启用失败', err)
            this.$message.error('批量启用失败')
          })
          .finally(() => {
            this.loading = false
          })
      }).catch(() => {
        this.$message.info('已取消操作')
      })
    },
    // 批量禁用
    handleBatchDisable() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请至少选择一项')
        return
      }
      
      this.$confirm(`确认禁用选中的${this.multipleSelection.length}个套餐?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        const ids = this.multipleSelection.map(item => item.id).join(',')
        updateSetmealStatus(ids, 0)
          .then(res => {
            if (res.code === 1) {
              this.$message.success('批量禁用成功')
              this.fetchSetmealList()
            } else {
              this.$message.error(res.msg || '批量禁用失败')
            }
          })
          .catch(err => {
            console.error('批量禁用失败', err)
            this.$message.error('批量禁用失败')
          })
          .finally(() => {
            this.loading = false
          })
      }).catch(() => {
        this.$message.info('已取消操作')
      })
    }, */
    // 批量删除
    handleBatchDelete() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请至少选择一项')
        return
      }
      
      this.$confirm(`确认删除选中的${this.multipleSelection.length}个套餐?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        const ids = this.multipleSelection.map(item => item.id).join(',')
        deleteSetmeal(ids)
          .then(res => {
            if (res.code === 1) {
              this.$message.success('批量删除成功')
              this.fetchSetmealList()
            } else {
              this.$message.error(res.msg || '批量删除失败')
            }
          })
          .catch(err => {
            console.error('批量删除失败', err)
            this.$message.error('批量删除失败')
          })
          .finally(() => {
            this.loading = false
          })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // 状态变更
    handleStatusChange(row) {
      const statusText = row.status === 1 ? '启用' : '禁用'
      this.loading = true
      updateSetmealStatus(row.id, row.status)
        .then(res => {
          if (res.code === 1) {
            this.$message.success(`套餐「${row.name}」已${statusText}`)
          } else {
            // 恢复原状态
            row.status = row.status === 1 ? 0 : 1
            this.$message.error(res.msg || `${statusText}失败`)
          }
        })
        .catch(err => {
          // 恢复原状态
          row.status = row.status === 1 ? 0 : 1
          console.error(`${statusText}失败`, err)
          this.$message.error(`${statusText}失败`)
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 多选变更
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 页码改变
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchSetmealList()
    },
    // 每页条数改变
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.fetchSetmealList()
    }
  }
}
</script>

<style scoped>
.setmeal-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.operation-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>